﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

using Telerik.Cms.Engine;
using Telerik.Libraries;

namespace Telerik.Sitefinity.Services.Migration
{
	public partial class MigrationExportService : IMigrationExportService
	{
		public Message GetLibrariesList()
		{
			List<MigrationItemContentDefinition> output = new List<MigrationItemContentDefinition>();

			foreach (KeyValuePair<string, ContentProviderBase> provider in m_AllProviders)
			{
				// Check if the provider is Libraries' default provider
				if (provider.Value is Telerik.Libraries.Data.DefaultProvider)
				{
					string providerName = provider.Key;
					LibraryManager libraryManager = new LibraryManager(providerName);

					IList libraryList = libraryManager.GetAllLibraries(0, 0, "Name ASC");
					AddGenericContentGuidToList(libraryList, output, providerName, String.Empty);
				}
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetLibrariesListResponse", output);
		}

		public Message GetSingleLibrary(Message libraryDefinitionParam)
		{
			MigrationItemContentDefinition param = libraryDefinitionParam.GetBody<MigrationItemContentDefinition>();

			LibraryManager libraryManager = new LibraryManager(param.ProviderName);
			ILibrary libraryItem = libraryManager.GetLibrary(param.Id);

			MigrationLibrary result = new MigrationLibrary();
			result.DateCreated = libraryItem.DateCreated;
			result.Id = libraryItem.ID;
			result.MaxFiles = libraryItem.MaxFiles;
			result.MaxFileSize = libraryItem.MaxFileSize;
			result.MaxSize = libraryItem.MaxSize;
			result.Name = libraryItem.Name;
			result.Owner = libraryItem.Owner;
			result.RequireCaching = libraryItem.RequireCaching;
			result.TypeName = libraryItem.TypeName;

			IList libraryItems = libraryManager.GetContent(0, 0, "Name ASC", libraryItem.ID);
			AddGenericContentToList(libraryItems, result.Documents, "Libraries", String.Empty);

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetSingleLibraryResponse", result);
		}
	}
}
